<template>
	<view class="container">
		<view class="editor-page">
			<view class="page-header">
				<view class="title-area">
					<text class="page-title">{{title || '富文本编辑器'}}</text>
				</view>
				<view class="action-area">
					<template v-if="isFullScreenMode">
						<button class="action-btn return-btn" @click="returnToEdit">保存并返回</button>
					</template>
					<template v-else>
						<button class="action-btn save-btn" @click="saveContent">保存内容</button>
						<button class="action-btn cancel-btn" @click="cancelEdit">取消编辑</button>
					</template>
				</view>
			</view>
			
			<!-- 富文本编辑器主体 -->
			<view class="editor-container">
				<!-- 编辑器工具栏 -->
				<view class="editor-toolbar">
					<!-- 加粗按钮 -->
					<view class="toolbar-btn" @click="formatText('bold')" :class="{ active: formats.bold }">
						<text class="toolbar-icon">B</text>
					</view>
					
					<!-- 字体大小选择 -->
					<view class="toolbar-dropdown">
						<view class="toolbar-btn dropdown-toggle" @click="showFontSizeSelector = !showFontSizeSelector">
							<text class="toolbar-icon">A</text>
							<text class="dropdown-arrow">▼</text>
						</view>
						<view class="dropdown-menu" v-if="showFontSizeSelector">
							<view class="dropdown-item" @click="formatText('fontSize', '14px'); showFontSizeSelector = false">
								<text class="dropdown-text">小</text>
							</view>
							<view class="dropdown-item" @click="formatText('fontSize', '16px'); showFontSizeSelector = false">
								<text class="dropdown-text">中</text>
							</view>
							<view class="dropdown-item" @click="formatText('fontSize', '18px'); showFontSizeSelector = false">
								<text class="dropdown-text">大</text>
							</view>
						</view>
					</view>
					
					<!-- 文字颜色选择 -->
					<view class="toolbar-dropdown">
						<view class="toolbar-btn dropdown-toggle" @click="showColorSelector = !showColorSelector">
							<view class="color-icon" :style="{ backgroundColor: currentColor || '#000000' }"></view>
							<text class="dropdown-arrow">▼</text>
						</view>
						<view class="dropdown-menu color-menu" v-if="showColorSelector">
							<view class="color-grid">
								<view class="color-item" 
									v-for="(color, index) in colorList" 
									:key="index" 
									:style="{ backgroundColor: color }"
									@click="formatText('color', color); showColorSelector = false; currentColor = color;">
								</view>
							</view>
						</view>
					</view>
					
					<!-- 对齐方式 -->
					<view class="toolbar-btn" @click="formatText('align', 'left')" :class="{ active: formats.align === 'left' }">
						<view class="align-icon">
							<view class="align-line short-line left-align"></view>
							<view class="align-line medium-line left-align"></view>
							<view class="align-line full-line"></view>
						</view>
					</view>
					
					<view class="toolbar-btn" @click="formatText('align', 'center')" :class="{ active: formats.align === 'center' }">
						<view class="align-icon">
							<view class="align-line full-line"></view>
							<view class="align-line center-line"></view>
							<view class="align-line full-line"></view>
						</view>
					</view>
					
					<view class="toolbar-btn" @click="formatText('align', 'right')" :class="{ active: formats.align === 'right' }">
						<view class="align-icon">
							<view class="align-line short-line right-align"></view>
							<view class="align-line medium-line right-align"></view>
							<view class="align-line full-line"></view>
						</view>
					</view>
					
					<!-- 添加首行缩进按钮 -->
					<view class="toolbar-btn" @click="formatText('textIndent', '2em')" :class="{ active: formats.textIndent }">
						<view class="indent-icon">
							<view class="indent-first-line"></view>
							<view class="indent-line"></view>
							<view class="indent-line"></view>
						</view>
					</view>

					<view class="toolbar-btn" @click="formatText('align', 'justify')" :class="{ active: formats.align === 'justify' }">
						<view class="align-icon">
							<view class="align-line full-line"></view>
							<view class="align-line full-line"></view>
							<view class="align-line full-line"></view>
						</view>
					</view>
					
					<!-- 项目符号 -->
					<view class="toolbar-btn" @click="formatText('list', 'bullet')" :class="{ active: formats.list === 'bullet' }">
						<view class="bullet-icon">
							<view class="bullet-item">
								<view class="bullet-dot"></view>
								<view class="bullet-line"></view>
							</view>
							<view class="bullet-item">
								<view class="bullet-dot"></view>
								<view class="bullet-line"></view>
							</view>
						</view>
					</view>
					
					<!-- 图片插入按钮 -->
					<view class="toolbar-btn" @click="insertImage">
						<text class="toolbar-icon">🖼️</text>
					</view>
					
					<!-- 清除格式按钮 -->
					<view class="toolbar-btn" @click="clearFormat">
						<text class="toolbar-icon">清除</text>
					</view>
					
					
					
					<!-- 添加撤销按钮 -->
					<view class="toolbar-btn" @click="undo">
						<text class="toolbar-icon">↩️</text>
					</view>
				</view>
				
				<!-- 编辑器主体 -->
				<editor 
					id="editor" 
					class="editor" 
					:placeholder="placeholder || '请输入内容...'" 
					@ready="onEditorReady" 
					@input="onEditorInput"
					@statuschange="onStatusChange"
					:show-img-resize="true"
					:show-img-toolbar="true"
					:show-img-size="true"
					:read-only="false"
				></editor>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				editorCtx: null,  // 编辑器上下文
				editorReadyFlag: false, // 编辑器是否准备就绪
				formats: {}, // 记录当前应用的格式
				showFontSizeSelector: false, // 控制字体大小选择器显示
				showColorSelector: false, // 控制颜色选择器显示
				currentColor: '#000000', // 当前选中的颜色
				inputTimer: null, // 输入防抖定时器
				fixedLineHeight: '2em', // 固定行高
				fixedFontSize: '16px', // 固定字体大小
				
				// 编辑器参数
				editorContent: '', // 编辑器HTML内容
				editorDelta: null, // 编辑器Delta内容
				title: '', // 页面标题
				placeholder: '', // 编辑器占位符
				
				// 颜色选择列表
				colorList: [
					'#000000', '#333333', '#666666', '#999999', 
					'#ff0000', '#ff9900', '#ffff00', '#00ff00',
					'#00ffff', '#0000ff', '#9900ff', '#ff00ff'
				],
				isFullScreenMode: false
			}
		},
		onLoad(options) {
			// 获取传递的参数
			if (options.title) {
				this.title = decodeURIComponent(options.title);
			}
			
			if (options.placeholder) {
				this.placeholder = decodeURIComponent(options.placeholder);
			}
			
			// 判断是否是全屏模式
			this.isFullScreenMode = options.mode === 'fullscreen';
			
			// 获取缓存的内容
			try {
				const cachedContent = uni.getStorageSync('rich_text_editor_content');
				if (cachedContent) {
					// 解析JSON字符串
					const contentData = JSON.parse(cachedContent);
					
					// 恢复HTML内容
					if (contentData.html) {
						this.editorContent = contentData.html;
					}
					
					// 恢复Delta内容
					if (contentData.delta) {
						this.editorDelta = contentData.delta;
					}
					
					console.log('已从缓存恢复编辑器内容');
				}
			} catch (e) {
				console.error('从缓存恢复内容失败', e);
			}
		},
		onUnload() {
			// 页面卸载时自动保存内容到缓存
			// 注意：这只是作为意外关闭的备份，正常应该通过"保存"按钮保存
			this._saveToCache();
		},
		methods: {
			// 保存内容到缓存
			_saveToCache() {
				if (!this.editorContent) return;
				
				try {
					// 将内容和delta都保存到缓存
					const contentData = {
						html: this.editorContent,
						delta: this.editorDelta
					};
					
					uni.setStorageSync('rich_text_editor_content', JSON.stringify(contentData));
					console.log('编辑器内容已保存到缓存');
				} catch (e) {
					console.error('保存内容到缓存失败', e);
				}
			},
			
			// 保存内容并返回
			saveContent() {
				// 先保存到缓存
				this._saveToCache();
				
				// 构建返回数据
				const pages = getCurrentPages();
				if (pages.length > 1) {
					const prevPage = pages[pages.length - 2];
					// 调用上一个页面的方法
					if (prevPage.$vm && typeof prevPage.$vm.onRichTextEditorComplete === 'function') {
						prevPage.$vm.onRichTextEditorComplete({
							html: this.editorContent,
							delta: this.editorDelta
						});
					}
				}
				
				// 返回上一页
				uni.navigateBack();
			},
			
			// 取消编辑并返回
			cancelEdit() {
				uni.showModal({
					title: '确认取消',
					content: '取消后编辑的内容将不会保存，确定要取消吗？',
					success: (res) => {
						if (res.confirm) {
							// 清除缓存
							uni.removeStorageSync('rich_text_editor_content');
							uni.navigateBack();
						}
					}
				});
			},
			
			// 编辑器准备就绪
			onEditorReady() {
				// #ifdef MP-WEIXIN || H5
				uni.createSelectorQuery().select('#editor').context((res) => {
					this.editorCtx = res.context;
					this.editorReadyFlag = true;
					console.log('编辑器已准备就绪');
					
					// 恢复内容
					if (this.editorContent) {
						this._restoreContent();
					}
					
					// 默认应用固定行高和字体大小
					setTimeout(() => {
						this._applyFixedStyles();
					}, 500);
				}).exec();
				// #endif
			},
			
			// 恢复内容
			_restoreContent() {
				if (!this.editorCtx) return;
				
				// 优先使用Delta格式恢复内容
				if (this.editorDelta) {
					console.log('使用Delta格式恢复内容');
					this.editorCtx.setContents({
						delta: this.editorDelta,
						success: () => {
							console.log('Delta格式恢复成功');
							setTimeout(() => {
								this._applyFixedStyles();
							}, 300);
						},
						fail: (err) => {
							console.error('Delta格式恢复失败:', err);
							// 如果Delta恢复失败，尝试HTML恢复
							this._restoreContentWithHtml();
						}
					});
				} else {
					// 使用HTML格式恢复
					this._restoreContentWithHtml();
				}
			},
			
			// 使用HTML格式恢复内容
			_restoreContentWithHtml() {
				if (!this.editorCtx) return;
				
				let content = this.editorContent || '';
				// 确保内容是有效的HTML
				if (!content.trim().startsWith('<')) {
					content = `<p>${content}</p>`;
				}
				
				console.log('使用HTML格式恢复内容');
				this.editorCtx.setContents({
					html: content,
					success: () => {
						console.log('HTML格式恢复成功');
						setTimeout(() => {
							this._applyFixedStyles();
						}, 300);
					},
					fail: (err) => {
						console.error('HTML格式恢复失败:', err);
					}
				});
			},
			
			// 监听编辑器输入 - 使用防抖优化
			onEditorInput(e) {
				// 清除之前的定时器
				if (this.inputTimer) {
					clearTimeout(this.inputTimer);
				}
				
				// 设置新的定时器，延迟300ms执行以提高性能
				this.inputTimer = setTimeout(() => {
					// 保存delta格式的内容 - 这是官方推荐的做法
					if (e.detail.delta) {
						this.editorDelta = JSON.parse(JSON.stringify(e.detail.delta)); // 深拷贝避免引用问题
					}
					
					// 更新html内容
					this.editorContent = e.detail.html || '';
					console.log('编辑器内容已更新');
				}, 300);
			},
			
			// 监听编辑器状态变化
			onStatusChange(e) {
				// 更新当前格式状态
				this.formats = e.detail;
			},
			
			// 应用文本格式
			formatText(name, value) {
				if (!this.editorCtx) return;
				this.editorCtx.format(name, value);
				
				// 如果修改的是行高或字体大小，更新保存的固定值
				if (name === 'lineHeight') {
					this.fixedLineHeight = value;
				} else if (name === 'fontSize') {
					this.fixedFontSize = value;
				}
			},
			
			// 清除格式
			clearFormat() {
				if (!this.editorCtx) return;
				this.editorCtx.removeFormat();
				
				// 清除格式后重新应用固定的行高和字体大小
				setTimeout(() => {
					this._applyFixedStyles();
				}, 100);
			},
			
			// 插入图片
			insertImage() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						uni.showLoading({
							title: '上传中...'
						});
						
						const tempFilePath = res.tempFilePaths[0];
						
						// 上传图片到服务器
						uni.uploadFile({
							url: 'https://你的服务器图片上传接口',  // 替换为实际的图片上传接口
							filePath: tempFilePath,
							name: 'file',
							success: (uploadRes) => {
								try {
									const data = JSON.parse(uploadRes.data);
									// 假设服务器返回的格式是 { url: "图片地址" }
									const imageUrl = data.url;
									
									// 插入图片到编辑器
									this.editorCtx.insertImage({
										src: imageUrl,
										alt: '图片',
										width: '100%',  // 默认宽度
										success: () => {
											console.log('插入图片成功');
										}
									});
								} catch (e) {
									console.error('解析上传结果失败', e);
									uni.showToast({
										title: '图片上传失败',
										icon: 'none'
									});
								}
							},
							fail: () => {
								uni.showToast({
									title: '图片上传失败',
									icon: 'none'
								});
							},
							complete: () => {
								uni.hideLoading();
							}
						});
					}
				});
			},
			
			// 应用固定样式 - 确保行间距一致
			_applyFixedStyles() {
				if (!this.editorCtx) return;
				
				try {
					// 应用行高
					this.editorCtx.format('lineHeight', this.fixedLineHeight);
					
					// 应用字体大小
					this.editorCtx.format('fontSize', this.fixedFontSize);
					
					console.log('应用了固定样式');
				} catch (error) {
					console.error('应用固定样式出错:', error);
				}
			},
			
			// 直接应用样式（主要方法）
			_applyStylesDirectly() {
				if (!this.editorCtx) return;
				
				try {
					// 使用format命令而不是setContents
					this.editorCtx.format('lineHeight', this.fixedLineHeight);
					this.editorCtx.format('fontSize', this.fixedFontSize);
					console.log('直接应用样式成功');
				} catch (error) {
					console.error('直接应用样式失败:', error);
				}
			},
			
			// 返回编辑页面
			returnToEdit() {
				// 自动保存内容到缓存
				this._saveToCache();
				
				// 构建返回数据
				const pages = getCurrentPages();
				if (pages.length > 1) {
					const prevPage = pages[pages.length - 2];
					// 调用上一个页面的方法
					if (prevPage.$vm && typeof prevPage.$vm.onRichTextEditorComplete === 'function') {
						prevPage.$vm.onRichTextEditorComplete({
							html: this.editorContent,
							delta: this.editorDelta
						});
					}
				}
				
				// 返回上一页
				uni.navigateBack();
			},
			
			// 添加撤销方法
			undo() {
				if (!this.editorCtx) return;
				this.editorCtx.undo();
			}
		}
	}
</script>

<style>
	.container {
		width: 100%;
		min-height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #f8f8f8;
	}
	
	.editor-page {
		flex: 1;
		display: flex;
		flex-direction: column;
		padding: 20rpx;
	}
	
	.page-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 20rpx;
	}
	
	.title-area {
		flex: 1;
	}
	
	.page-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}
	
	.action-area {
		display: flex;
		gap: 20rpx;
	}
	
	.action-btn {
		padding: 16rpx 24rpx;
		border-radius: 8rpx;
		font-size: 28rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.save-btn {
		background-color: #1BAE76;
		color: #fff;
	}
	
	.cancel-btn {
		background-color: #f5f5f5;
		color: #666;
		border: 1px solid #ddd;
	}
	
	.return-btn {
		background-color: #1BAE76;
		color: #fff;
		border: none;
		width: auto;
		min-width: 200rpx;
		white-space: nowrap;
		padding: 0 30rpx;
	}
	
	/* 编辑器容器 */
	.editor-container {
		flex: 1;
		display: flex;
		flex-direction: column;
		border: 1px solid #ddd;
		border-radius: 8rpx;
		background-color: #fff;
		overflow: hidden;
		min-height: 600rpx;
	}
	
	/* 工具栏样式 */
	.editor-toolbar {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		padding: 12rpx;
		background-color: #f8f8f8;
		border-bottom: 1px solid #eee;
		position: sticky;
		top: 0;
		z-index: 10;
		gap: 12rpx; /* 统一按钮间距 */
	}
	
	/* 工具栏按钮 */
	.toolbar-btn {
		width: 64rpx;
		height: 64rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #fff;
		border-radius: 6rpx;
		border: 1px solid #ddd;
		transition: all 0.2s;
	}
	
	.toolbar-btn:active {
		background-color: #f0f0f0;
	}
	
	.toolbar-btn.active {
		background-color: #1BAE76;
		color: #fff;
		border-color: #1BAE76;
	}
	
	.toolbar-icon {
		font-size: 28rpx;
		font-weight: bold;
	}
	
	/* 工具栏下拉菜单 */
	.toolbar-dropdown {
		position: relative;
	}
	
	.dropdown-toggle {
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.dropdown-arrow {
		font-size: 20rpx;
		margin-left: 4rpx;
	}
	
	.dropdown-menu {
		position: absolute;
		top: 100%;
		left: 0;
		width: 140rpx;
		background-color: #fff;
		border: 1px solid #ddd;
		border-radius: 6rpx;
		box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
		z-index: 100;
		margin-top: 8rpx;
	}
	
	.color-menu {
		width: 240rpx;
	}
	
	.dropdown-item {
		padding: 12rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.dropdown-item:active {
		background-color: #f5f5f5;
	}
	
	.dropdown-text {
		font-size: 26rpx;
		color: #333;
	}
	
	/* 颜色选择器 */
	.color-icon {
		width: 24rpx;
		height: 24rpx;
		border-radius: 50%;
		border: 1px solid #ddd;
	}
	
	.color-grid {
		display: flex;
		flex-wrap: wrap;
		padding: 10rpx;
	}
	
	.color-item {
		width: 40rpx;
		height: 40rpx;
		margin: 4rpx;
		border-radius: 4rpx;
		border: 1px solid #ddd;
	}
	
	/* 对齐方式图标 */
	.align-icon {
		display: flex;
		flex-direction: column;
		gap: 4rpx;
		width: 32rpx;
	}
	
	.align-line {
		height: 4rpx;
		background-color: #333;
	}
	
	.short-line {
		width: 60%;
	}
	
	.medium-line {
		width: 80%;
	}
	
	.full-line {
		width: 100%;
	}
	
	.center-line {
		width: 60%;
		margin: 0 auto;
	}
	
	/* 为左对齐添加样式 */
	.left-align {
		margin-right: auto;
		margin-left: 0;
	}
	
	/* 为右对齐添加样式 */
	.right-align {
		margin-left: auto;
		margin-right: 0;
	}
	
	/* 项目符号图标 */
	.bullet-icon {
		display: flex;
		flex-direction: column;
		gap: 4rpx;
	}
	
	.bullet-item {
		display: flex;
		align-items: center;
		gap: 4rpx;
	}
	
	.bullet-dot {
		width: 6rpx;
		height: 6rpx;
		border-radius: 50%;
		background-color: #333;
	}
	
	.bullet-line {
		width: 24rpx;
		height: 2rpx;
		background-color: #333;
	}
	
	/* 首行缩进图标 */
	.indent-icon {
		display: flex;
		flex-direction: column;
		gap: 6rpx;
		width: 32rpx;
	}
	
	.indent-line {
		height: 3rpx;
		width: 100%;
		background-color: #333;
	}
	
	.indent-first-line {
		height: 3rpx;
		width: 70%;
		margin-left: 30%;
		background-color: #333;
	}
	
	/* 活跃状态下改变图标颜色 */
	.toolbar-btn.active .indent-line,
	.toolbar-btn.active .indent-first-line {
		background-color: #fff;
	}
	
	/* 编辑器 */
	.editor {
		flex: 1;
		min-height: 500rpx;
		padding: 20rpx;
		box-sizing: border-box;
	}
</style> 